﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace NumericTextBox
{
    public class TextChangedBehavior : Behavior<TextBox>
    {
        protected override void OnAttached()
        {
            if (AttachedProperties.GetIsUsingMinMaxValue(AssociatedObject))
                AssociatedObject.PreviewTextInput += AssociatedObject_PreviewTextInput;
            base.OnAttached();
        }

        void AssociatedObject_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!DoesStringContainsOnlyDigits(e.Text))
            {
                e.Handled = true;
            }
            int minValue = AttachedProperties.GetMinimumValue(AssociatedObject);
            int maxValue = AttachedProperties.GetMaximumValue(AssociatedObject);

            int numericValue;
            if (int.TryParse(AssociatedObject.Text + e.Text, out numericValue))
            {
                if (numericValue < minValue || numericValue > maxValue)
                    e.Handled = true;
            }
        }

        private bool DoesStringContainsOnlyDigits(string input)
        {
            for (int index = 0; index < input.Length; index++)
            {
                if (!char.IsDigit(input[index]))
                    return false;
            }
            return true;
        }

        protected override void OnDetaching()
        {
            if (AttachedProperties.GetIsUsingMinMaxValue(AssociatedObject))
                AssociatedObject.PreviewTextInput -= AssociatedObject_PreviewTextInput;
            base.OnDetaching();
        }
    }
}
